package javax;

/**
 * Created by xupeng20 on 2019/1/15.
 */
public class Xp_0120 {
    /**
     *  链表求和1：你有两个用链表代表的整数，其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序，
     * 使得第一个数字位于链表的开头。写出一个函数将两个整数相加，用链表形式返回和。
     */
    public static class ListNode{
        int val;
        ListNode next;
        public ListNode(int x){
            val = x;
        }
    }
    public static ListNode addLists(ListNode l1, ListNode l2) {
        // write your code here
        int sum = l1.val + l2.val;
        ListNode n1 = l1.next;
        ListNode n2 = l2.next;
        ListNode head = new ListNode(sum%10);
        ListNode temp = head;
        sum /= 10;
        while(n1 != null || n2 != null || sum != 0){
            sum +=(((n1 == null) ? 0 : n1.val) + ((n2 == null) ? 0 : n2.val));
            temp.next = new ListNode(sum%10);
            temp = temp.next;
            n1=((n1 == null) ? null : n1.next);
            n2=((n2 == null) ? null : n2.next);
            sum /= 10;
        }
        return head;
    }
    public ListNode add(ListNode L1,ListNode L2){
        int sum = L1.val+L2.val;
        ListNode n1 = L1.next;
        ListNode n2 = L2.next;
        ListNode head = new ListNode(sum%10);
        ListNode temp = head;
        sum /= 10 ;
        while (n1 != null || n2 != null || sum!=0 ){
            sum += (((n1 == null) ? 0:n1.val)+((n2 == null) ? 0:n2.val));
            temp.next = new ListNode(sum%10);
            temp = temp.next;

            n1 =(n1 == null) ? null : n1.next;
            n2 =(n2 == null) ? null : n2.next;

            sum /=10 ;
        }
        return head;
    }
    public static void main(String[] args){
        ListNode L1 = new ListNode(0);
        ListNode L2 = new ListNode(0);
        Xp_0120.addLists(L1,L2);
    }
}
